package dao;
import utils.DruidUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public class BasicDao<T>{

    public QueryRunner queryRunner = new QueryRunner(DruidUtil.dataSource);

    /**
     * dml操作
     * @param sql
     * @param params
     * @return
     */
    public int update(String sql, Object... params) {

        Connection connect = null;
        try {
            connect = DruidUtil.getConnect();
            return queryRunner.update(connect, sql, params);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            DruidUtil.closeConnect(connect);
        }
    }

    /**
     * 批量获取数据
     * @param sql
     * @param clazz
     * @param params
     * @return
     */
    public List<T> getMulit(String sql, Class<T>clazz, Object...params) {

        Connection connection = null;

        try {
            connection = DruidUtil.getConnect();
            return queryRunner.query(connection,sql,new BeanListHandler<T>(clazz),params);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            DruidUtil.closeConnect(connection);
        }
    }

    /**
     * 获取单行数据
     * @param sql
     * @param clazz
     * @param params
     * @return
     */
    public T getSingle(String sql, Class<T> clazz, Object...params) {

        Connection connection = null;
        try {
            connection = DruidUtil.getConnect();
            return queryRunner.query(connection,sql,new BeanHandler<T>(clazz),params);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            DruidUtil.closeConnect(connection);
        }
    }

    /**
     * 获取单行单列
     * @param sql
     * @param params
     * @return
     */
    public T getColumn(String sql, Object...params) {

        Connection connection = null;
        try {
            connection = DruidUtil.getConnect();
            return queryRunner.query(connection,sql,new ScalarHandler<>(),params);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            DruidUtil.closeConnect(connection);
        }

    }

    public int getTotal(String sql, Object...params) {
        Connection connection = null;
        try {
            connection = DruidUtil.getConnect();
            return ((Long) queryRunner.query(sql, new ScalarHandler<>(),params)).intValue();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            DruidUtil.closeConnect(connection);
        }
    }

}
